package A003_NagrajObraz;



import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map.Entry;

import javafx.scene.Node;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import A003_NagrajObraz.OsCheck.OSType;

import javax.swing.JTextField;

import org.eclipse.wb.swing.FocusTraversalOnArray;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import javax.swing.DropMode;

import java.awt.ComponentOrientation;



public class RECOfMany implements  ActionListener, WindowListener, KeyListener {
		
	/**
	 * 
	 */
	
	public JDialog dialog;
	private Frame owner;
	private transient LinkedList<BufferedImage> iTMPObrazow = null;
	private transient HashMap<String, LinkedList<BufferedImage>> iBibloteka;
	DateFormat dateFormat;
	Date date;
	
	private String iPathDefoult = "";
	JFileChooser chooser;
	String pathTemp = "/Users/tom/Desktop/test";

		
	private JSpinner iCzasProbki;
	int iczasprobki = 20;
	
	private JPanel iRamka_obraz;
	private JPanel iP_Obraz;
	private JPanel panel_1;
	private JPanel panel;
	private JPanel iParm1; //parametry szerokos pobieranego obrazka
	private JPanel panel_info;

	private JButton butnGOTOWOSC;
	private JButton btnNAGRYWAJ;
	private JButton btnReset;
	private JButton btnZapisz_1;
	
	private JButton btnSortuj;
	
	private JSpinner iWysokoscOb;
	private JSpinner iSzerokoscOb;
	private JLabel lblPOSort;

	private JLabel lblPrzedSort;
	private JButton btnWczytaj;
	
	private boolean iGotowyDoNagrywania=false;
	private boolean NAGRYWAM=false;
	private Robot rob;
	private BufferedImage iBuf; // zrzut spod kursorap
	private Image scaledImage;
	private Timer timer; //czestotliwosc probek
	public JTextArea log;
	
	private GlobalScreen GS;
	
	//pozycja i wielkosc ramki podczas nagrywania
	int iPozycjaKursoraX = 0, iPozycjaKursoraY=0, iSzerokoscRamki=0, iWysokoscRamki=0; String text;

	

	public RECOfMany() {
		


		

        
        
        
		iTMPObrazow = new LinkedList<BufferedImage>(); // pezchowuje temObrazkow
		iBibloteka = new HashMap<String, LinkedList<BufferedImage>>(); // przechowuje kolekce z temObrazow
		
		dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		date = new Date();

				
		if (OSType.MacOS == OsCheck.getOperatingSystemType()){
			iPathDefoult = "002-DoFi/SET/MAC/SZUKANE/";
			System.out.println("ścieżka " + iPathDefoult);

		} else if (OSType.Windows == OsCheck.getOperatingSystemType()) {
			iPathDefoult = "002-DoFi/SET/PC/SZUKANE/";
		}

		
		try {
			rob = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}

		try {
			String path = new java.io.File("..").getCanonicalPath();
				System.out.println("PATH \n" + path);
			//this.buf = ImageIO.read(new File(path+"/002-DoFi/src/NagrywarkaObrazkow/iKatObraz/centerConf.bmp"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		try {
			GlobalScreen.registerNativeHook();
		} catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
		}
		
		 System.out.println("Hook state: "+ GlobalScreen.isNativeHookRegistered());
		GS = GlobalScreen.getInstance();
		GS.addNativeKeyListener(new NativeKeyListener() {
			
			@Override
			public void nativeKeyTyped(NativeKeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void nativeKeyReleased(NativeKeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void nativeKeyPressed(NativeKeyEvent arg0) {
				// TODO Auto-generated method stub
	            System.err.println("getModifiers " + (arg0.getModifiers()+ " RawCode "+ arg0.getRawCode() + " ID " + arg0.getID() + " getWhen " + arg0.getWhen() + " CHAR " + arg0.getKeyChar()));
	            
	            switch (arg0.getRawCode()){
	            case (NativeKeyEvent.VK_UP):
	            	if (!NAGRYWAM){
		            	if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_STANDARD){//SHIFT
		            		iWysokoscOb.setValue( ((long) iWysokoscOb.getValue()) + 10);
		            	} else if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_LEFT){ //CTR
		            		iPozycjaKursoraY = iPozycjaKursoraY + 1;
		            	} else {
		            		iWysokoscOb.setValue( ( ((long) iWysokoscOb.getValue()) + 1) );
		            	}
	            	}
	            	break;
	            case (NativeKeyEvent.VK_DOWN):
	            	if (!NAGRYWAM){
		            	if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_STANDARD){//SHIFT
			            	iWysokoscOb.setValue( ((long) iWysokoscOb.getValue()) - 10);
		            	} else if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_LEFT){ //CTR
		            		iPozycjaKursoraY = iPozycjaKursoraY - 1;
		            	} else {
		            		iWysokoscOb.setValue( ( ((long) iWysokoscOb.getValue()) - 1 ) );
		            	}
	            	}
	            	break;
	            case (NativeKeyEvent.VK_RIGHT):
	            	if (!NAGRYWAM){
		            	if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_STANDARD){//SHIFT
			            	iSzerokoscOb.setValue( ((long) iSzerokoscOb.getValue()) + 10);
		            	} else if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_LEFT){ //CTR
		            		iPozycjaKursoraX = iPozycjaKursoraX + 1;
		            	} else {
		            		iSzerokoscOb.setValue( ( ((long) iSzerokoscOb.getValue()) + 1) );
		            	}
	            	}	 
	            break;
	            case (NativeKeyEvent.VK_LEFT):
	            	if (!NAGRYWAM){
		            	if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_STANDARD){//SHIFT
			            	iSzerokoscOb.setValue( ((long) iSzerokoscOb.getValue()) - 10);
		            	} else if (arg0.getModifiers() == NativeKeyEvent.KEY_LOCATION_LEFT){ //CTR
		            		iPozycjaKursoraX = iPozycjaKursoraX - 1;
		            	} else {
		            		iSzerokoscOb.setValue( ( ((long) iSzerokoscOb.getValue()) -1 ) );
		            	}
	            	}
	            break;
	            }

			}
		});
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(Container parent, String title) {
		
		owner = null;
		if (parent instanceof Frame) owner = (Frame) parent;
		else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
		
		if (dialog == null || dialog.getOwner()!=owner){
			dialog = new JDialog(owner, true);
		}
		
		dialog = new JDialog();
		dialog.getContentPane().setLocale(new Locale("pl"));
		dialog.setAlwaysOnTop(true);

		dialog.setTitle(title);
		dialog.setBounds(100, 100, 264, 552);
		dialog.getContentPane().setLayout(null);

		iRamka_obraz = new JPanel();
		iRamka_obraz.setBounds(5, 6, 156, 156);
		iRamka_obraz.setBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)));
		iRamka_obraz.setBackground(Color.DARK_GRAY);
		iRamka_obraz.setLayout(null);
		dialog.getContentPane().add(iRamka_obraz);
		
		dialog.addWindowListener(new WindowListener() {
			
			@Override
			public void windowOpened(WindowEvent e) {	}
			
			@Override
			public void windowIconified(WindowEvent e) {	}
			
			@Override
			public void windowDeiconified(WindowEvent e) {	}
			
			@Override
			public void windowDeactivated(WindowEvent e) {	}
			
			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("clouse window");
				 GlobalScreen.unregisterNativeHook();
					SwingUtilities.getWindowAncestor(dialog).dispose();
					System.exit(0);
			}
			
			@Override
			public void windowClosed(WindowEvent e) {	}
			
			@Override
			public void windowActivated(WindowEvent e) {	}
		});
		
		iP_Obraz = new iObraz();
		iRamka_obraz.add(iP_Obraz);

		panel_1 = new JPanel();
		panel_1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				System.out.println(e.getKeyChar());

			}
		});
		
		iParm1 = new JPanel();
		iParm1.setBounds(5, 195, 244, 73);
		dialog.getContentPane().add(iParm1);
		iParm1.setBorder(null);
		iParm1.setLayout(new GridLayout(0, 3, 0, 0));
		
		//http://www.java2s.com/Tutorial/Java/0240__Swing/DisablingKeyboardEditinginaJSpinnerComponent.htm
		iSzerokoscOb = new JSpinner(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));
	    JFormattedTextField tf = ((JSpinner.DefaultEditor) iSzerokoscOb.getEditor()).getTextField();
	    tf.setEditable(false);
	    tf.setBackground(Color.white);
	    tf.setFocusable(false);
		//iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));


	    // The value of the spinner can still be programmatically changed
	    //iSzerokoscOb.setValue(new Integer(100));

		iSzerokoscOb.setToolTipText("Szeroko\u015B\u0107 pr\u00F3bki 1-301px");

		iParm1.add(iSzerokoscOb);
		
		JLabel lblSzer_1 = new JLabel("szer.");
		lblSzer_1.setHorizontalAlignment(SwingConstants.CENTER);
		lblSzer_1.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblSzer_1);
		
		horizontalStrut = Box.createHorizontalStrut(20);
		horizontalStrut.setEnabled(false);
		iParm1.add(horizontalStrut);
		
		
		iWysokoscOb = new JSpinner(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));
		JFormattedTextField tf2 = ((JSpinner.DefaultEditor) iWysokoscOb.getEditor()).getTextField();
	    tf2.setEditable(false);
	    tf2.setBackground(Color.white);
	    tf2.setFocusable(false);
		iWysokoscOb.setToolTipText("Wysoko\u015B\u0107 pr\u00F3bki 1-301px");
		iWysokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				//iSzerokoscOb.setValue((long) iWysokoscOb.getValue());
			}
		});
		//iWysokoscOb.setModel(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));
		iWysokoscOb.setFont(new Font("Tahoma", Font.BOLD, 11));
		iParm1.add(iWysokoscOb);
		
		JLabel lblWys = new JLabel("wys.");
		lblWys.setHorizontalAlignment(SwingConstants.CENTER);
		lblWys.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblWys);
		
		horizontalStrut_1 = Box.createHorizontalStrut(20);
		horizontalStrut_1.setVisible(false);
		iParm1.add(horizontalStrut_1);
		
		iCzasProbki = new JSpinner(new SpinnerNumberModel(new Integer(0), new Integer(0), new Integer(500), new Integer(1)));
		JFormattedTextField tf3 = ((JSpinner.DefaultEditor) iCzasProbki.getEditor()).getTextField();
	    tf3.setEditable(false);
	    tf3.setBackground(Color.white);
	    tf3.setFocusable(false);
		iCzasProbki.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iczasprobki = (int)iCzasProbki.getValue();
				timer.setDelay(iczasprobki);
			}
		});
		iCzasProbki.setToolTipText("Szybko\u015B\u0107 probki obrazu 10-500ms");
		iParm1.add(iCzasProbki);
		
		JLabel lblms = new JLabel("ms");
		lblms.setHorizontalAlignment(SwingConstants.CENTER);
		lblms.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblms);
		
		Component horizontalStrut_3 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_3);
		iParm1.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{iSzerokoscOb, iWysokoscOb, iCzasProbki, horizontalStrut, horizontalStrut_3, lblSzer_1, lblWys, horizontalStrut_1, lblms}));
		
		panel = new JPanel();
		panel.setBounds(5, 168, 245, 20);
		dialog.getContentPane().add(panel);
		panel.setLayout(new GridLayout(0, 1, 0, 0));
		
		JTextField iNazwa = new JTextField();
		iNazwa.setFocusTraversalKeysEnabled(false);
		iNazwa.setHorizontalAlignment(SwingConstants.CENTER);
		iNazwa.setForeground(Color.GRAY);
		iNazwa.setText("nazwa");
		panel.add(iNazwa);
		iNazwa.setColumns(10);
		panel.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{iNazwa}));
		panel_1.setBounds(5, 273, 244, 84);
		dialog.getContentPane().add(panel_1);
		panel_1.setLayout(new GridLayout(0, 2, 0, 0));
		
		//====================GOTOWOSC=====================================
		butnGOTOWOSC = new JButton("");
		butnGOTOWOSC.setMnemonic(KeyEvent.VK_KP_LEFT);
		final ImageIcon ikona1 = 
				new ImageIcon(RECOfMany.class.getResource
						("/A003_NagrajObraz/Images/play20x20.png"));
		final ImageIcon ikona2 = 
				new ImageIcon(RECOfMany.class.getResource
						("/A003_NagrajObraz/Images/stop20x20.png"));
		if (iGotowyDoNagrywania == false)
			{butnGOTOWOSC.setIcon(ikona1);}
		else if (iGotowyDoNagrywania == true)
			{butnGOTOWOSC.setIcon(ikona2);}
		
		dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
		
		butnGOTOWOSC.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if (iGotowyDoNagrywania == false){
					butnGOTOWOSC.setIcon(ikona2);
					//--------------
					iGotowyDoNagrywania = true;
					btnNAGRYWAJ.setEnabled(true);
				} else{ // if is true
					if (iTMPObrazow.size() > 0){
						
					}
					butnGOTOWOSC.setIcon(ikona1);
					iGotowyDoNagrywania = false;
					//--------------
					NAGRYWAM = false;
					// akcaj jesli do sotownia jest lista
					if  (NAGRYWAM == false && iTMPObrazow.size()>0){
					}
					btnNAGRYWAJ.setEnabled(false);
				}
				
				if (!iGotowyDoNagrywania && !NAGRYWAM){ //sterowanie klawiszami
					
					//==wpis do bibloteki
					if (iTMPObrazow.size()>0){
						iBibloteka.put(iNazwa.getText() + "_" + (iBibloteka.size()+1), iTMPObrazow);
						iLog("Wpis do Bibloteki " + iNazwa.getText() + "_" + iTMPObrazow.size(), 1);
						iTMPObrazow = new LinkedList<BufferedImage>(); // tworze nowa instancje
					}
					dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				} else if (iGotowyDoNagrywania && !NAGRYWAM){
					dialog.getRootPane().setDefaultButton(btnNAGRYWAJ);
				} else {dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				}
				
			}
		});	
		butnGOTOWOSC.setToolTipText("Naci\u015Bnij \"ENTER\" zablokujesz ramk\u0119 podgladu");
		panel_1.add(butnGOTOWOSC);

		//====================NAGRYWAJ=====================================
		btnNAGRYWAJ = new JButton("NAGRYWAJ");
		btnNAGRYWAJ.setEnabled(false);
		btnNAGRYWAJ.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (iGotowyDoNagrywania == false){
					return;
				}
				NAGRYWAM = true;
				btnNAGRYWAJ.setEnabled(false);
			
				if (!iGotowyDoNagrywania && !NAGRYWAM){ //sterowanie klawiszami
					dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				} else if (iGotowyDoNagrywania && !NAGRYWAM){
					dialog.getRootPane().setDefaultButton(btnNAGRYWAJ);
				} else {

					dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				}
			}
			
		});



		btnNAGRYWAJ.setToolTipText("Naci\u015Bnij \"S\" odblokujesz ramk\u0119 podgladu");
		panel_1.add(btnNAGRYWAJ);
		
		btnReset = new JButton("RESET");
		btnReset.setToolTipText("resetuje bufory z obrazami");
		btnReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (iGotowyDoNagrywania == false && NAGRYWAM ==false){
					Reset(0);
				}
			}
		});
		panel_1.add(btnReset);
		
		btnZapisz_1 = new JButton("ZAPISZ");
		btnZapisz_1.setToolTipText("zapisujesz obrazki zawarte w buforze");
		btnZapisz_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		btnZapisz_1.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent arg0) {
				iZapisz();
			}
			
		});
		
		btnSortuj = new JButton("SORTUJ");
		btnSortuj.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				iSortuj();
			}
		});
		btnSortuj.setToolTipText("czysci bufory z takich samych obrazow");
		panel_1.add(btnSortuj);
		
		btnWczytaj = new JButton("WCZYTAJ");
		btnWczytaj.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				iWczytaj();
			}
			
		});
		

		btnWczytaj.setToolTipText("mozesz wczytac inne schematy tej samej wielkości obrazki co w buforze");
		panel_1.add(btnWczytaj);
		panel_1.add(btnZapisz_1);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(5, 360, 245, 165);
		panel_2.setLayout(new GridLayout(0, 1, 0, 0));
		dialog.getContentPane().add(panel_2);
		
		log = new JTextArea();
		log.setFont(new Font("Lucida Grande", Font.PLAIN, 8));
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
		panel_2.add(log);
        JScrollPane logScrollPane = new JScrollPane(log);
        panel_2.add(logScrollPane);
        
        panel_info = new JPanel();
        panel_info.setBounds(166, 6, 84, 95);
        dialog.getContentPane().add(panel_info);
        panel_info.setLayout(new GridLayout(3, 1, 0, 0));
        
        lblPrzedSort = new JLabel("0");
        lblPrzedSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPrzedSort);
        
        lblPOSort = new JLabel("0");
        lblPOSort.setFont(new Font("Lucida Grande", Font.PLAIN, 28));
        lblPOSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPOSort);
        
        lblBibloteka = new JLabel("0");
        lblBibloteka.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblBibloteka);

				
		timer = new Timer(iczasprobki, action);
		timer.start();
		
		dialog.setVisible(true);

	}
	
	private ActionListener action = new ActionListener() {
		public void actionPerformed(ActionEvent ae) {
			//System.out.println("starat");
			if(!iGotowyDoNagrywania){
				iPozycjaKursoraX = igetCurrentPosX();
				iPozycjaKursoraY = igetCurrentPosY();
			}
			if(!NAGRYWAM){
				iSzerokoscRamki = (int)(long)iSzerokoscOb.getValue();
				iWysokoscRamki  = (int)(long)iWysokoscOb.getValue();				
			}
			
			if(NAGRYWAM){
				btnReset.setEnabled(false);
				btnWczytaj.setEnabled(false);
				btnZapisz_1.setEnabled(false);
				btnSortuj.setEnabled(false);
				
			} else{
				btnReset.setEnabled(true);
				btnWczytaj.setEnabled(true);
				btnZapisz_1.setEnabled(true);
				btnSortuj.setEnabled(true);
			}
			
			if (iSzerokoscRamki < 3 ) {
				iSzerokoscRamki = 3;
				iSzerokoscOb.setValue((long)iSzerokoscRamki);
			}
			if (iWysokoscRamki < 3) {
				iWysokoscRamki = 3;
				iWysokoscOb.setValue((long) iWysokoscRamki);
			}
			iBuf = rob.createScreenCapture(new Rectangle (iPozycjaKursoraX-iSzerokoscRamki/2, iPozycjaKursoraY-iWysokoscRamki/2, iSzerokoscRamki, iWysokoscRamki));
			if (NAGRYWAM == true && iTMPObrazow != null) {
				iTMPObrazow.add(iBuf);
			}
			lblPrzedSort.setText(""+iTMPObrazow.size());
			lblBibloteka.setText(""+iBibloteka.size());

			if (iTMPObrazow == null){
				text = "00pu"; 
			} else text = ""+iTMPObrazow.size();
						
			if (!iTMPObrazow.isEmpty()) {
				iSzerokoscOb.setEnabled(false);
				iWysokoscOb.setEnabled(false);
			} else {
				iSzerokoscOb.setEnabled(true);
				iWysokoscOb.setEnabled(true);
			}
			
			panel_info.repaint();
			iRamka_obraz.repaint();
		}
	};
	/**
	 * @param a jeśli 0 to zostanie wyświtlone okno dialogowe czy kasowac bufor
	 * 			jeśli 1 to zostanie skasowany bufor
	 * @return
	 */
	protected boolean Reset(int a) {
		 Object[] options = { "OK", "CANCEL" };
		 
		switch (a){
		case 0:	
			int JP = JOptionPane.showOptionDialog(null, "OK zresetujesz bufor", "Uwaga RESET",
	        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
			
			if (JP == JOptionPane.CANCEL_OPTION){ return false;}
			if (JP == JOptionPane.OK_OPTION){
				iTMPObrazow.clear();
				iBibloteka.clear();}
			lblPOSort.setText(""+ 0);
			return true;
		case 1:
			iTMPObrazow.clear();
			iBibloteka.clear();
			iLog("Kasuję Bufor ", 2);
			lblPOSort.setText(""+ 0);
			return true;
		}
		return false;
	}

	//============================================================================
	private int igetCurrentPosX(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.print("POZYCJA MOUSA X: " + pointer.getLocation().x + " ");
		return pointer.getLocation().x;
	}
	private int igetCurrentPosY(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.println("POZYCJA MOUSA Y: " + pointer.getLocation().y);
		return pointer.getLocation().y;
	}
	

	private void iSortuj(){
		LinkedList<BufferedImage> obj;
		Iterator<String> it = iBibloteka.keySet().iterator();

		System.out.println("" + iBibloteka.toString());
		
		while (it.hasNext()){
			String key = it.next();
			System.out.println("KEY " + key);
			obj = iBibloteka.get(key);
			IN = obj.size();
			iBodySort(obj);
		}
	}
	
	private int wilkoscIN, IN;

	private void iBodySort(LinkedList<BufferedImage> obj){

		wilkoscIN = obj.size();
		
		BufferedImage el1=null, el2=null;
		
		for (int a = 0; a < obj.size(); a++){
			for (int b = a+1; b < obj.size(); b++){
				
				el1 = obj.get(a);
				el2 = obj.get(b);
				
				if (el1 != null && el2 != null) {
					if (el1.getWidth() != el2.getWidth() || el1.getHeight() != el2.getHeight()) {
						JOptionPane.showConfirmDialog(dialog, "OBRAZY SĄ NIE ZGONE WIELKOŚCIOWO");
						return;
					}
					
					if (iPorownaj(el1, el2)) {
						obj.remove(b);
					}; 
				}				
			}
		}
		lblPOSort.setText(""+obj.size());
		

		if ( obj.size() != wilkoscIN) iBodySort(obj);
		else {
			iLog("ilosc obrazów po sortowniu.." + obj.size( ), 2);
			System.out.println("Obiekt size IN " + IN);
			System.out.println("Obiekt size OUT " + obj.size());
		}
		
		return;
	}

	//porownaj jesli true - to obrazy sa taki same
	private boolean iPorownaj (BufferedImage el1, BufferedImage el2){
		
		for (int y = 0; y < el1.getHeight(); y++){
			for (int x = 0; x < el1.getWidth(); x++){
				
				if (el1.getRGB(x, y) != el2.getRGB(x, y)) {
						return false;
				}
			}
		}
		
		return true;
	}
	
	//===========================//ZAPISZ//============================================
	private void iZapisz(){
		
		 Object[] options = { "TAK", "NIE" };
		 
			int JP = JOptionPane.showOptionDialog(null, "Chcesz SORTOWAC przed zapisem", "Uwaga przed ZAPISANIEM", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
			             null, options, options[0]);
			if (JP == JOptionPane.CANCEL_OPTION){
				return;
			}
			
			if (JP == JOptionPane.OK_OPTION){
				iSortuj();
			}
			
			JFileChooser chooser = new JFileChooser();
			   // chooser.setCurrentDirectory(new java.io.File (iInitLinki.iGlobalPathSET + iInitLinki.iKatSys + "SZUKANE/"));
			    chooser.setCurrentDirectory(new java.io.File (pathTemp));
			
				chooser.setFileFilter(new FileNameExtensionFilter("BMP", "bmp"));
			
				int result = chooser.showSaveDialog(null);
			    
				if (result == JFileChooser.CANCEL_OPTION){
					return;
				}
				    
				//File file = chooser.getSelectedFile();
			    if (result == JFileChooser.APPROVE_OPTION) { 
			    	//iPathFolder = chooser.getCurrentDirectory();
			      //System.out.println("getCurrentDirectory(): " +  iPathFolder);
			      System.out.println("getSelectedFile() : " +  chooser.getSelectedFile());
			      }
			    else { System.out.println("No Selection "); }
			    
				
		LinkedList<BufferedImage> obj;
		Iterator<String> it = iBibloteka.keySet().iterator();

		System.out.println("" + iBibloteka.toString());
		
		while (it.hasNext()){
			String key = it.next();
			System.out.println("KEY " + key);
			obj = iBibloteka.get(key);
			IN = obj.size();
			iBodyZapisz(obj, key, chooser);
		}
	}

	private void iBodyZapisz(LinkedList<BufferedImage> obj, String key, JFileChooser chooser) {

		System.out.println("Zapisuje elementow " + obj.size());
		if (obj.size() == 0) return;
			
		Iterator<BufferedImage> it = obj.iterator();
		BufferedImage buf = null;
		File iPathFolder = null;
		int licz = 0;
		
	    
	    LinkedList<int[][]> tmpLL = new LinkedList<int[][]>();
	    
	    while (it.hasNext()){
	    	buf =  (BufferedImage) it.next();
	    	File outputfile = new File(chooser.getSelectedFile() + "_" + key + "_" +licz++ +".bmp");
		    try {
				ImageIO.write(buf, "bmp", outputfile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		    
	    	iLog("" + outputfile.getAbsoluteFile().getName(), 1); 
	    	
	    	// dla zapisu calosci do int
	    	
	    	int [][] tmpbufINT = new int [buf.getWidth()][buf.getHeight()];
	    	
	    	for (int y = 0; y < buf.getHeight(); y++){
	    		for (int x = 0; x< buf.getWidth(); x++){
	    			tmpbufINT [x][y] = buf.getRGB(x, y);
	    		}
	    	}
	    	
	    	tmpLL.push(tmpbufINT);
	    }
	    //serializacja
	    //http://stackoverflow.com/questions/15058663/how-to-serialize-an-object-that-includes-bufferedimages
	    
		 String path = chooser.getCurrentDirectory() + "/" + chooser.getSelectedFile().getName() + "_" + key + ".ser";
		 System.out.println("Zapis " + path);
		 		    	 
		 try
	     {
	         FileOutputStream fileOut = new FileOutputStream(path);
	         ObjectOutputStream out = new ObjectOutputStream(fileOut);
	         out.writeObject(tmpLL);
	         out.close();
	         fileOut.close();
	         System.out.printf("Serialized data is saved in /tmp/employee.ser");
	      }catch(IOException i)
	      {
	          i.printStackTrace();
	      }
		 
	
	}

	@SuppressWarnings("unchecked")
	private void iWczytaj() {
		
		JFileChooser chooser = new JFileChooser();
	    chooser.setCurrentDirectory(new java.io.File (pathTemp));
			
	     chooser.setFileFilter(new FileNameExtensionFilter("ser", "ser"));
	
	     int rezultat = chooser.showOpenDialog(null);
	     
			if (rezultat == JFileChooser.CANCEL_OPTION){
				return;
			}
			
		LinkedList<int[][]> tmpLL = new LinkedList<int[][]>(); 
	      
		try{
			String path = chooser.getCurrentDirectory() + "/" +chooser.getSelectedFile().getName();
	    	System.out.println("Odczyt " + path);
	    	 
	      FileInputStream fis = new FileInputStream(path);
	      ObjectInputStream ois = new ObjectInputStream(fis);
	      tmpLL  = (LinkedList<int[][]>) ois.readObject();
	
	      ois.close();
	
	      System.out.println (tmpLL);
	
	  } catch (FileNotFoundException e) {e.printStackTrace();
	  } catch (IOException e) {e.printStackTrace();
	     } catch (ClassNotFoundException e) {e.printStackTrace();
	     }
		
	
		if (!tmpLL.isEmpty()){
			iLog("Wczytuję z pliku elementów "+ tmpLL.size(), 1);
			int [][] first = tmpLL.getFirst();
			iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(first.length), new Long(1), new Long(701), new Long(1)));
			iWysokoscOb.setModel(new SpinnerNumberModel(new Long(first[0].length), new Long(1), new Long(701), new Long(1)));
		}
		
		LinkedList<BufferedImage> obj = new LinkedList<BufferedImage>();
		
		BufferedImage tmpBuf;
		for (int[][] to : tmpLL){
			tmpBuf = new BufferedImage(to.length, to[0].length, iBuf.getType());
			
			for (int y = 0; y < to[0].length; y++){
				for (int x = 0; x < to.length; x++){
					tmpBuf.setRGB(x, y, to[x][y]);
				}
			}
			obj.add(tmpBuf);
		}
		iBibloteka.put(chooser.getSelectedFile().getName(), obj);
		obj = new LinkedList<BufferedImage>();
		
		System.out.println (iTMPObrazow.toString());
	}


	/**
	 * @param log - String
	 * @param a - 	jeśli 1 to wpis z datą
	 * 				jeśli 2 to wpis bez daty
	 */
	private void iLog(String log, int a) {
		switch (a){
		case 1:
			this.log.append(java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) +" " + log + "\n");
			break;
		case 2:
			this.log.append("" + log + "\n");
			break;
		}
	}


	class iObraz extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		int wFrameObraz;
		int hFrameObraz;
		
		public iObraz() {
			super();
	
			setBackground(Color.gray);
			setBounds(new Rectangle(10, 11, 136, 134));
			setBorder(BorderFactory.createLineBorder(Color.black));
			setLayout(new FlowLayout(FlowLayout.CENTER)); 
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
	
			wFrameObraz = iP_Obraz.getSize().width;
			hFrameObraz = iP_Obraz.getSize().height;
			if ( iBuf !=  null ){
				scaledImage = (iBuf.getScaledInstance(wFrameObraz, wFrameObraz, (Image.SCALE_AREA_AVERAGING)));
				g.drawImage(scaledImage, 0, 0, null);
			}
		}
	}
			
		@Override
		public void windowOpened(WindowEvent e) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("zmaykasz okno)");		
		}
		
		@Override
		public void windowClosed(WindowEvent e) {
			System.runFinalization();
			System.exit(0);
		}
		
		@Override
		public void windowIconified(WindowEvent e) {	}
		
		@Override
		public void windowDeiconified(WindowEvent e){	}
		
		@Override
		public void windowActivated(WindowEvent e) {	}
		
		@Override
		public void windowDeactivated(WindowEvent e) {	}
		
		/*@Override
		public void nativeKeyPressed(NativeKeyEvent arg0) {
				int a=arg0.getKeyCode();
				System.out.println("nacisniety klawisz-"+a+" "+arg0.getKeyText(a)+" "+ arg0.paramString());
				switch (a){
					case (KeyEvent.VK_MINUS):
						if(iczasprobki<=0)break; 
						iCzasProbki.setValue(iczasprobki-10);
						break;
					case (KeyEvent.VK_EQUALS):
						if(iczasprobki>0)break;
						iCzasProbki.setValue(iczasprobki+10);
						break;
					case KeyEvent.VK_ADD: 
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())<3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						break;
					case KeyEvent.VK_SUBTRACT: 
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())< 3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						break;
					case KeyEvent.VK_LEFT: 
						System.out.println("LEFT)");
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						break;
					case KeyEvent.VK_RIGHT: 
						break;	
					case KeyEvent.VK_ESCAPE: 
						GlobalScreen.unregisterNativeHook();
						System.runFinalization();
						System.exit(2);
						break;
				}
		}*/
		

		
		@Override
		public void actionPerformed(ActionEvent e) {	}
		
		
		@Override
		public void keyPressed(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}

		@Override
		public void keyReleased(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}

		@Override
		public void keyTyped(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}
		

		/**
		 * Laduje do LinkedList
		 * @param buf
		 */
		public void iIN (BufferedImage buf){
			if (iTMPObrazow == null) {
				iTMPObrazow = new LinkedList<BufferedImage>();
			}
			iTMPObrazow.add(buf);
		}
		
		/**
		 * Usuwa zbędne elmenty z tablicy
		 * @throws IOException 
		 */
		private Component horizontalStrut;
		private Component horizontalStrut_1;
		private JLabel lblBibloteka;
		
		/**
		 * Launch the application.
		 */
		public static void main(String[] args) {
			System.out.println("test");
				RECOfMany window = new RECOfMany();
				window.initialize(null, "NAGRYWARKA");
			System.out.println("test");

		}
}
